package com.zhentao.datacontrol.controller;

import com.zhentao.datacontrol.domain.dto.RuleGroupDTO;
import com.zhentao.datacontrol.service.RuleGroupService;
import com.zhentao.subscription.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/datacontrol/groups")
@CrossOrigin(origins = "*")
public class RuleGroupController {

    @Autowired
    private RuleGroupService ruleGroupService;

    /**
     * 获取分组树形结构
     */
    @GetMapping("/tree")
    public R<List<RuleGroupDTO>> getGroupTree() {
        try {
            List<RuleGroupDTO> tree = ruleGroupService.getGroupTree();
            return R.ok(tree);
        } catch (Exception e) {
            // 如果表不存在，返回空列表而不是500错误
            if (e.getMessage() != null && e.getMessage().contains("doesn't exist")) {
                return R.ok(new ArrayList<>());
            }
            throw e;
        }
    }

    /**
     * 获取顶级分组列表
     */
    @GetMapping("/top")
    public R<List<RuleGroupDTO>> getTopLevelGroups() {
        List<RuleGroupDTO> groups = ruleGroupService.getTopLevelGroups();
        return R.ok(groups);
    }

    /**
     * 获取子分组列表
     */
    @GetMapping("/children/{parentId}")
    public R<List<RuleGroupDTO>> getChildGroups(@PathVariable Long parentId) {
        List<RuleGroupDTO> children = ruleGroupService.getChildGroups(parentId);
        return R.ok(children);
    }

    /**
     * 获取分组详情
     */
    @GetMapping("/{id}")
    public R<RuleGroupDTO> getGroupDetail(@PathVariable Long id) {
        RuleGroupDTO group = ruleGroupService.getGroupDetail(id);
        if (group == null) {
            return R.error("分组不存在");
        }
        return R.ok(group);
    }

    /**
     * 创建分组
     */
    @PostMapping
    public R<Long> createGroup(@Valid @RequestBody RuleGroupDTO groupDTO) {
        try {
            Long id = ruleGroupService.createGroup(groupDTO);
            return R.ok(id);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 更新分组
     */
    @PutMapping("/{id}")
    public R<Void> updateGroup(@PathVariable Long id, @Valid @RequestBody RuleGroupDTO groupDTO) {
        try {
            groupDTO.setId(id);
            boolean success = ruleGroupService.updateGroup(groupDTO);
            return success ? R.ok() : R.error("更新失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除分组
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteGroup(@PathVariable Long id) {
        try {
            boolean success = ruleGroupService.deleteGroup(id);
            return success ? R.ok() : R.error("删除失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 移动分组
     */
    @PostMapping("/{id}/move")
    public R<Void> moveGroup(@PathVariable Long id, 
                           @RequestParam Long targetParentId, 
                           @RequestParam Integer targetSortOrder) {
        try {
            boolean success = ruleGroupService.moveGroup(id, targetParentId, targetSortOrder);
            return success ? R.ok() : R.error("移动失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 检查分组名称是否存在
     */
    @GetMapping("/check-name")
    public R<Boolean> checkGroupNameExists(@RequestParam String groupName, 
                                         @RequestParam(required = false) Long parentId,
                                         @RequestParam(required = false) Long excludeId) {
        boolean exists = ruleGroupService.checkGroupNameExists(groupName, parentId, excludeId);
        return R.ok(exists);
    }

    /**
     * 批量更新排序
     */
    @PostMapping("/sort")
    public R<Void> updateSortOrders(@RequestBody SortOrderRequest request) {
        try {
            boolean success = ruleGroupService.updateSortOrders(request.getIds(), request.getSortOrders());
            return success ? R.ok() : R.error("排序更新失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 排序请求对象
     */
    public static class SortOrderRequest {
        private List<Long> ids;
        private List<Integer> sortOrders;

        public List<Long> getIds() { return ids; }
        public void setIds(List<Long> ids) { this.ids = ids; }

        public List<Integer> getSortOrders() { return sortOrders; }
        public void setSortOrders(List<Integer> sortOrders) { this.sortOrders = sortOrders; }
    }
}
